package com.gzx.plugin.tjzy.modular.sms.api.strategy.xd.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.gzx.plugin.tjzy.modular.founds.service.GzxFoundsFlowService;
import com.gzx.plugin.tjzy.modular.sms.api.strategy.SMSStrategy;
import com.gzx.plugin.tjzy.modular.sms.api.strategy.common.dto.CommonSmsSendReqDto;
import com.gzx.plugin.tjzy.modular.sms.api.strategy.common.dto.CommonSmsSendRespDto;
import com.gzx.plugin.tjzy.modular.sms.api.strategy.xd.dto.SMSXDReceiptRespDto;
import com.gzx.plugin.tjzy.modular.sms.api.strategy.xd.dto.SMSXDReplyRespDto;
import com.gzx.plugin.tjzy.modular.sms.api.strategy.yz.dto.SMSYZSendRespDto;
import com.gzx.plugin.tjzy.modular.sms.api.template.SmsTemplateMethod;
import com.gzx.plugin.tjzy.modular.sms.batch.consts.SMSYZConstant;
import com.gzx.plugin.tjzy.modular.sms.batch.enums.GzxSmsSendStatusEnum;
import com.gzx.plugin.tjzy.modular.sms.batch.service.GzxSmsDbService;
import com.gzx.plugin.tjzy.modular.sms.receipt.consts.GzxSendStatusMappingConstant;
import com.gzx.plugin.tjzy.modular.sms.receipt.entity.GzxSmsReceipt;
import com.gzx.plugin.tjzy.modular.sms.receipt.service.GzxSmsReceiptService;
import com.gzx.plugin.tjzy.modular.sms.record.service.GzxSmsRecordService;
import com.gzx.plugin.tjzy.modular.sms.reply.entity.GzxSmsReply;
import com.gzx.plugin.tjzy.modular.sms.reply.service.GzxSmsReplyService;
import com.gzx.plugin.tjzy.modular.supplier.consts.GzxSupplierConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import vip.xiaonuo.common.util.CommonDateUtil;
import vip.xiaonuo.common.util.CommonHttpUtil;

import java.util.*;

/**
 * @author zjt
 * @description
 * @date 2025/7/21 15:28
 */
@Slf4j
@Service
public class SMSXDStrategyImpl extends SmsTemplateMethod implements SMSStrategy {

    @Value("${sms.xd.url}")
    private String url;

    @Value("${sms.xd.account}")
    private String account;

    @Value("${sms.xd.password}")
    private String password;

    @Value("${sms.xd.extno}")
    private String extno;

    private static final String ACTION = "action";

    private static final String ACCOUNT = "account";

    private static final String PASSWORD = "password";

    public SMSXDStrategyImpl(GzxSmsDbService smsDbService, GzxSmsRecordService smsRecordService, GzxSmsReceiptService smsReceiptService, GzxFoundsFlowService foundsFlowService, GzxSmsReplyService smsReplyService) {
        super(smsDbService, smsRecordService, smsReceiptService, foundsFlowService, smsReplyService);
    }

    /**
     * 获取当前供应商
     *
     * @return
     */
    @Override
    public String getCurrentSupplierCode() {
        return GzxSupplierConstant.XD;
    }

    /**
     * 获取短信签名
     *
     * @param city
     * @return
     */
    @Override
    protected String getSignName(String city) {
        if ("天津".equals(city)) {
            return "【天津自贸试验区普惠金融调解中心】";
        }
        if ("盐城".equals(city)) {
            return "【盐城市盐南高新区金和金融调解中心】";
        }
        return "";
    }

    /**
     * 开始发送短信
     *
     * @param commonSmsSendReqDtoList 发送短信的集合
     * @return
     */
    @Override
    protected List<CommonSmsSendRespDto> startSend(List<CommonSmsSendReqDto> commonSmsSendReqDtoList) {
        Map<String, String> smsParam = new HashMap<>();
        Map<String, String> phoneMap = new HashMap<>();
        for (CommonSmsSendReqDto commonSmsSendReqDto : commonSmsSendReqDtoList) {
            smsParam.put(commonSmsSendReqDto.getPhone(), modifySmsSignature(commonSmsSendReqDto.getSignCity(), commonSmsSendReqDto.getMessage()));
            phoneMap.put(commonSmsSendReqDto.getPhone(), commonSmsSendReqDto.getSupplierOrder());
        }
        Map<String, Object> reqBody = new HashMap<>();
        reqBody.put(ACTION, SMSYZConstant.ONE_ONE);
        reqBody.put(ACCOUNT, account);
        reqBody.put(PASSWORD, password);
        reqBody.put("extno", extno);
        reqBody.put("mobileContentKvp", smsParam);
        try {
            String respBody = CommonHttpUtil.post(url, null, JSON.toJSONString(reqBody), "迅达短信发送");
            SMSYZSendRespDto smsyzSendRespDto = JSON.parseObject(respBody, SMSYZSendRespDto.class);
            if (smsyzSendRespDto != null && smsyzSendRespDto.getStatus() == 0 && CollectionUtil.isNotEmpty(smsyzSendRespDto.getList())) {
                List<CommonSmsSendRespDto> commonSmsSendRespDtoList = new ArrayList<>();
                for (SMSYZSendRespDto.PhoneResult phoneResult : smsyzSendRespDto.getList()) {
                    String supplierOrder = phoneMap.get(phoneResult.getMobile());
                    Integer result = (supplierOrder.endsWith(GzxSupplierConstant.XD) && phoneResult.getResult() != 0) ? GzxSmsSendStatusEnum.FINAL_FAIL.getCode() : phoneResult.getResult();
                    commonSmsSendRespDtoList.add(new CommonSmsSendRespDto(phoneResult.getMobile(), phoneResult.getMid(), result));
                }
                return commonSmsSendRespDtoList;
            }
            return defaultResp(commonSmsSendReqDtoList, GzxSmsSendStatusEnum.FAIL.getCode(), GzxSupplierConstant.XD);
        } catch (Exception e) {
            log.error("调用迅达短信发送接口出现异常", e);
            return defaultResp(commonSmsSendReqDtoList, GzxSmsSendStatusEnum.FAIL.getCode(), GzxSupplierConstant.XD);
        }
    }

    /**
     * 同步短信回执
     *
     * @return
     */
    @Override
    protected List<GzxSmsReceipt> startSyncReceipt() {
        Map<String, Object> reqBody = new HashMap<>();
        reqBody.put(ACTION, SMSYZConstant.RECEIPT);
        reqBody.put(ACCOUNT, account);
        reqBody.put(PASSWORD, password);
        try {
            String respBody = CommonHttpUtil.post(url, null, JSON.toJSONString(reqBody), "迅达短信状态查询");
            SMSXDReceiptRespDto smsxdReceiptRespDto = JSON.parseObject(respBody, SMSXDReceiptRespDto.class);
            List<GzxSmsReceipt> smsReceiptList = new ArrayList<>();
            if (smsxdReceiptRespDto != null && smsxdReceiptRespDto.getStatus() == 0 && CollectionUtil.isNotEmpty(smsxdReceiptRespDto.getList())) {
                String currentDate = CommonDateUtil.getCurrentTimeStr();
                for (SMSXDReceiptRespDto.XDReceiptDetail xdReceiptDetail : smsxdReceiptRespDto.getList()) {
                    GzxSmsReceipt smsReceipt = new GzxSmsReceipt();
                    smsReceipt.setSupplierCode(GzxSupplierConstant.XD);
                    smsReceipt.setFlagType(xdReceiptDetail.getFlag());
                    smsReceipt.setPhone(xdReceiptDetail.getMobile());
                    smsReceipt.setMsgId(xdReceiptDetail.getMid());
                    smsReceipt.setSendTime(xdReceiptDetail.getTime());
                    smsReceipt.setResultCode(xdReceiptDetail.getStat());
                    smsReceipt.setMappingStatus(GzxSupplierConstant.XD_SUCCESS.equals(xdReceiptDetail.getStat()) ? GzxSendStatusMappingConstant.SUCCESS : GzxSendStatusMappingConstant.FAIL);
                    smsReceipt.setAllDetail(JSON.toJSONString(xdReceiptDetail));
                    smsReceipt.setCreateTime(currentDate);
                    smsReceiptList.add(smsReceipt);
                }
            }
            return smsReceiptList;
        } catch (Exception e) {
            log.error("调用迅达查询接口出现异常", e);
            return Collections.emptyList();
        }
    }

    /**
     * 开始同步短信回复
     *
     * @return
     */
    @Override
    protected List<GzxSmsReply> startSyncReply() {
        Map<String, Object> reqBody = new HashMap<>();
        reqBody.put(ACTION, SMSYZConstant.REPLY);
        reqBody.put(ACCOUNT, account);
        reqBody.put(PASSWORD, password);
        try {
            String respBody = CommonHttpUtil.post(url, null, JSON.toJSONString(reqBody), "越众短信回复查询");
            SMSXDReplyRespDto smsxdReplyRespDto = JSON.parseObject(respBody, SMSXDReplyRespDto.class);
            List<GzxSmsReply> smsReplyList = new ArrayList<>();
            if (smsxdReplyRespDto != null && smsxdReplyRespDto.getStatus() == 0 && CollectionUtil.isNotEmpty(smsxdReplyRespDto.getList())) {
                String currentDate = CommonDateUtil.getCurrentTimeStr();
                for (SMSXDReplyRespDto.XDReplyDetail xdReplyDetail : smsxdReplyRespDto.getList()) {
                    xdReplyDetail.setContent(StringUtils.deleteWhitespace(xdReplyDetail.getContent()).replaceAll("[\\x00-\\x1F]", ""));
                    GzxSmsReply smsReply = new GzxSmsReply();
                    smsReply.setSupplierCode(GzxSupplierConstant.XD);
                    smsReply.setMsgId(xdReplyDetail.getMid());
                    smsReply.setPhone(xdReplyDetail.getMobile());
                    smsReply.setReplyContent(xdReplyDetail.getContent());
                    smsReply.setReplyTime(xdReplyDetail.getTime());
                    smsReply.setReplyDetail(JSON.toJSONString(xdReplyDetail));
                    smsReply.setCreateTime(currentDate);
                    smsReplyList.add(smsReply);
                }
            }
            return smsReplyList;
        } catch (Exception e) {
            log.error("调用越众短信回复查询接口出现异常", e);
            return Collections.emptyList();
        }
    }

    @Override
    protected boolean isSuccess(String resultCode) {
        return GzxSupplierConstant.XD_SUCCESS.equals(resultCode);
    }

    /**
     * 是否需要根据短信ID分组
     *
     * @return
     */
    @Override
    protected boolean isMsgIdGroup() {
        return false;
    }
}
